const express = require('express');
const bodyParser = require('body-parser');

const app = new express();
app.use(express.static('static'));
app.use(bodyParser.json());

var tasks = [
    {
        id: 1, companyName:'abc', category:'produce', createAt: new Date('2020-01-02'),
    },
    {
        id: 2, companyName:'def', category:'jiagong', createAt: new Date('2020-02-03'),
    }
]

var users = [
    {
        id: 1, username:'harry', password:'12345', level:'UPLOADER'
    },
    {
        id: 2, username:'garry', password:'12345', level:'ADMIN'
    },
]

function validUserAndReturnLevel(user){
    var data = {status: '', message: ''};
    for(item in users){
        if(user.username == item.username){
            if(user.password == item.password){
                data.status = 'ok';
                data.message = item.level
            }
            else{
                data.status = 'error';
                data.message = '密码错误';
            }
        }
        else{
            data.status = 'error';
            data.message = '用户名不存在';
        }
    }
    return data;
}

app.get('/api/tasks', (req, res)=>{
    const metadata = {totalCount: tasks.length}
    res.json({_metadata: metadata, records: tasks});
})

app.post('/api/login', (req, res)=>{
    res.json(validUserAndReturnLevel(req.body));
})

app.listen(3000, ()=>{
    console.log('started at 3000!')
})